import _ from "lodash";
import { typeClassName } from "@/pages/config/classNameMap";
import { mapMutations, mapActions, mapState } from "vuex";
const requireComponent = require.context("./", true, /[A-Z]\w+\.(vue)$/);
const comp = {};
requireComponent.keys().forEach((fileName) => {
  if (fileName != "./index.vue") {
    const componentConfig = requireComponent(fileName);
    const name = componentConfig.default.name;
    const componentName = _.camelCase(
      name
        .split("/")
        .pop()
        .replace(/\.\w+$/, "")
    );
    comp[componentName] = componentConfig.default || componentConfig;
  }
});
Object.keys(comp).map((key) => {
  comp[key].components = {...comp[key].components,...comp};
});
export default {
  components: comp,
  provide() {
    return {
      anc: this,
    };
  },
  computed: {
  },
  watch: {},
  created() {
    Object.keys(this.models).map((k) => {
      this.models[k].clz = this.$modelObject.create(this.models[k].modelType);
      this.models[k].clzs = this.$modelObject.create(
        this.models[k].modelType + "Collection"
      );
    });
  },
  mounted() {
    this.watchs.map(item=>{
      this.$watch(item.target,item.fn,{deep:item.deep})
    })
    this.$nextTick(() => {
      this.unwatch = this.$watch('vms', (newValue, oldValue) => {
        let flag = true;
        Object.keys(comp).map((k) => {
          if (!Object.keys(this.vms).includes(k)) {
            flag = false;
          }
        });
        this.completeLoad = flag;
      });
      this.init();
      if (process.env.NODE_ENV === "development") {
        console.log({ me: this, vms: this.vms, completeLoad:this.completeLoad });
      }
    });
  },
  destroyed(){
    this.unwatch();
  },
  data() {
    return {
      vms: {}, //页面组件vue实例
      completeLoad: false,
      me:this,
      watchs:[],
      models: {
        //模型
        // abc: typeClassName["abc"],
      },
      dataSet: {
        
      },
    };
  },
  methods: {
    init(){

    },
    rootRender(h, { root, node, data }){
      return h('span', {
              style: {
                  display: 'inline-block',
                  width: '100%'
              }
          },[
            h('Icon',{
              props: {
                  type: 'ios-folder-outline'
              },
              style: {
                  marginRight: '8px'
              }
            }),
            h('span', data.title)
          ]
        )
    },
    childRender(h, { root, node, data }){
      return h('span', {
              style: {
                  display: 'inline-block',
                  width: '100%'
              }
          },[
            h('Icon',{
              props: {
                  type: 'ios-git-branch'
              },
              style: {
                  marginRight: '8px'
              }
            }),
            h('span', data.title)
          ]
        )
    },
    navSelect(node){
      let item = this.dataSet.entries.find(e=>e.id===node.entry);
      item.subTab = node.id
      this.$set(this.dataSet,'currentEntry',item.id)
    },
    tabEntrySelect(id){
      let item = this.dataSet.entries.find(e=>e.id===id);
      let node = this.vms.navTree.findTreeNode('id',item.subTab);
      this.vms.navTree.handleSelect(node.nodeKey)
    },
    tabChildSelect(id){
      let node = this.vms.navTree.findTreeNode('id',id);
      this.vms.navTree.handleSelect(node.nodeKey)
    },
    switchTrace(entry,action){
      let trace = this.tracing.find(t=>t.from===entry.tag&&t.action===action);
      if(trace){
        let next = this.tracing.find(t=>t.from===trace.to); let node = {
          title:next.title,
          id:entry.id+'_'+next.from+this.uuid(),
          tag:trace.to,
          parentId:entry.id,
          entry:entry.entry,
          render: this.childRender,
        }
        this.dataSet.track.push(node);
        this.$nextTick(()=>{
          this.tabChildSelect(node.id)
        })
      }
    },
    closeTrace(node){
      let id = node.id;
      let item = this.dataSet.track.find(t=>t.id===id);
      if(item.parentId==='root'){
        return;
      }
      let parent = item.parentId;
      this.dataSet.track = this.dataSet.track.filter(t=>![id].includes(t.id));
      this.findChildren([id])
      this.$nextTick(()=>{
        this.tabChildSelect(parent)
      })
    },
    findChildren(ids){
      let children = [];
      this.dataSet.track.map(item=>{
        if(ids.includes(item.parentId)){
          children.push(item.id)
        }
      });
      if(children.length>0){
        this.dataSet.track = this.dataSet.track.filter(t=>!children.includes(t.id));
        this.findChildren(children)
      }

    },
    uuid (length = 8) {
      return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36);
    },
    loadPage(){

    },
    handleCreate() {
      this._setVmValue("createModal", "config.show", true);
    },
    createModalOk(loading) {
      this._$validateAll([this.vms.createView], (valid) => {
        if (valid) {
          this._setVmValue("createModal", "config.show", false);
        } else {
          this.$Message.info("请填写必填内容");
        }
      });
    },
    handleEdit(row) {
      this._setDataSet("", row)
      this._setVmValue("editModal", "config.show", true);
    },
    editModalOk() {
      this._$validateAll([this.vms.editView], (valid) => {
        if (valid) {
          this._setVmValue("editModal", "config.show", false);
        } else {
          this.$Message.info("请填写必填内容");
        }
      });
    },
    handleDelete(row) {
      this._$deleteConfirm(() => {
        
      });
    },
    /****************工具***************/
    _getModelFields(name, ...args) {
      let map = {};
      args.map((key) => {
        map[key] = this.models[name][key];
      });
      return map;
    },
    _getModelRecord(name) {
      return this.models[name].clz.record;
    },
    _setVmValue(name, key, value) {
      _.set(this.vms[name], key, value);
    },
    _getModelTpl(name){
      return this.$modelObject.getTpl(this.models[name].modelType);
    },
    _setDataSet(name, data) {
      this.dataSet[name] = data;
    },
    _modalShow(name){
      _.set(this.vms[name], 'config.show', true);
    },
    _modalClose(name){
      _.set(this.vms[name], 'config.show', false);
      _.set(this.vms[name], 'config.loading', false);
    },
    _tableLoading(name){
      _.set(this.vms[name], 'loading', true);
    },
    _tableUnLoading(name){
      _.set(this.vms[name], 'loading', false);
    },
    _resetForm(name){
      this.vms[name].resetFields();
    }
  },
};
